using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using JGSY.CMS.LowCode.Platform.Domain.Entities;
using JGSY.CMS.LowCode.Platform.Domain.Interfaces;
using JGSY.CMS.LowCode.Platform.Infrastructure.CmsDbContext;

namespace JGSY.CMS.LowCode.Platform.Infrastructure.Repositories
{
    /// <summary>
    /// 文章仓储实现
    /// 提供文章管理的完整数据访问功能，包含发布、搜索、统计等企业级功�?
    /// </summary>
    public class ArticleRepository : Repository<Article>, IArticleRepository
    {
        private readonly ILogger<ArticleRepository>? _logger;

        public ArticleRepository(LowCodeDbContext context, ILogger<ArticleRepository>? logger = null) : base(context)
        {
            _logger = logger;
        }

        #region IArticleRepository 实现

        /// <summary>
        /// 批量删除文章
        /// </summary>
        public async Task<int> BatchDeleteAsync(IEnumerable<long> ids)
        {
            try
            {
                var articles = await _context.Articles
                    .Where(a => ids.Contains(a.Id) && a.Status != 0)
                    .ToListAsync();

                foreach (var article in articles)
                {
                    article.Status = 0; // 软删�?
                    article.UpdatedAt = DateTime.UtcNow;
                }

                var deletedCount = articles.Count;
                await SaveChangesAsync();
                
                _logger?.LogInformation("Batch deleted {DeletedCount} articles", deletedCount);
                return deletedCount;
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "Failed to batch delete articles");
                throw;
            }
        }

        /// <summary>
        /// 删除文章
        /// </summary>
        public async Task DeleteAsync(long id)
        {
            try
            {
                var article = await _context.Articles.FindAsync(id);
                if (article != null)
                {
                    article.Status = 0; // 软删�?
                    article.UpdatedAt = DateTime.UtcNow;
                    await SaveChangesAsync();
                    
                    _logger?.LogInformation("Article soft deleted successfully with ID: {ArticleId}", id);
                }
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "Failed to delete article with ID: {ArticleId}", id);
                throw;
            }
        }

        /// <summary>
        /// 根据分类获取文章
        /// </summary>
        public async Task<IEnumerable<Article>> GetByCategoryAsync(long categoryId)
        {
            return await _context.Articles
                .Include(a => a.Category)
                .Where(a => a.CategoryId == categoryId && a.Status != 0)
                .OrderByDescending(a => a.CreatedAt)
                .ToListAsync();
        }

        /// <summary>
        /// 根据ID获取文章
        /// </summary>
    public async Task<Article?> GetByIdAsync(long id)
        {
            return await _context.Articles
                .Include(a => a.Category)
                .FirstOrDefaultAsync(a => a.Id == id && a.Status != 0);
        }

        /// <summary>
        /// 根据Slug获取文章
        /// </summary>
        public async Task<Article?> GetBySlugAsync(string slug)
        {
            return await _context.Articles
                .Include(a => a.Category)
                .FirstOrDefaultAsync(a => a.Slug == slug && a.Status != 0);
        }

        /// <summary>
        /// 获取最新文�?
        /// </summary>
        public async Task<IEnumerable<Article>> GetLatestArticlesAsync(int count = 10)
        {
            return await _context.Articles
                .Include(a => a.Category)
                .Where(a => a.Status == 1) // 已发�?
                .OrderByDescending(a => a.CreatedAt)
                .Take(count)
                .ToListAsync();
        }

        /// <summary>
        /// 分页获取文章
        /// </summary>
        public async Task<(IEnumerable<Article> Items, int TotalCount)> GetPagedAsync(
            int pageIndex, 
            int pageSize, 
            string? keyword = null, 
            long? categoryId = null, 
            byte? status = null,
            bool? isSticky = null)
        {
            var query = _context.Articles
                .Include(a => a.Category)
                .Where(a => a.Status != 0);

            // 关键词搜�?
            if (!string.IsNullOrWhiteSpace(keyword))
            {
                query = query.Where(a => a.Title.Contains(keyword) ||
                                   (a.Content != null && a.Content.Contains(keyword)) ||
                                   (a.Summary != null && a.Summary.Contains(keyword)));
            }

            // 分类过滤
            if (categoryId.HasValue)
            {
                query = query.Where(a => a.CategoryId == categoryId.Value);
            }

            // 状态过�?
            if (status.HasValue)
            {
                query = query.Where(a => a.Status == status.Value);
            }

            // 置顶过滤
            if (isSticky.HasValue)
            {
                query = query.Where(a => true);
            }

            var totalCount = await query.CountAsync();
            var items = await query
                .OrderByDescending(a => a.CreatedAt)
                .ThenByDescending(a => a.CreatedAt)
                .Skip(pageIndex * pageSize)
                .Take(pageSize)
                .ToListAsync();

            return (items, totalCount);
        }

        /// <summary>
        /// 获取热门文章
        /// </summary>
        public async Task<IEnumerable<Article>> GetPopularArticlesAsync(int count = 10)
        {
            return await _context.Articles
                .Include(a => a.Category)
                .Where(a => a.Status == 1) // 已发�?
                .OrderByDescending(a => a.ViewCount)
                .ThenByDescending(a => a.CreatedAt)
                .Take(count)
                .ToListAsync();
        }

        /// <summary>
        /// 获取置顶文章
        /// </summary>
        public async Task<IEnumerable<Article>> GetStickyArticlesAsync(int count = 10)
        {
            return await _context.Articles
                .Include(a => a.Category)
                .Where(a => a.Status == 1 )
                .OrderByDescending(a => a.CreatedAt)
                .Take(count)
                .ToListAsync();
        }

        /// <summary>
        /// 增加点赞�?
        /// </summary>
        public async Task<bool> IncrementLikeCountAsync(long id)
        {
            try
            {
                var article = await _context.Articles.FindAsync(id);
                if (article != null && article.Status == 1)
                {
                    article.LikeCount++;
                    article.UpdatedAt = DateTime.UtcNow;
                    await SaveChangesAsync();
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "Failed to increment like count for article ID: {ArticleId}", id);
                return false;
            }
        }

        /// <summary>
        /// 增加浏览�?
        /// </summary>
        public async Task<bool> IncrementViewCountAsync(long id)
        {
            try
            {
                var article = await _context.Articles.FindAsync(id);
                if (article != null && article.Status == 1)
                {
                    article.ViewCount++;
                    article.UpdatedAt = DateTime.UtcNow;
                    await SaveChangesAsync();
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "Failed to increment view count for article ID: {ArticleId}", id);
                return false;
            }
        }

        /// <summary>
        /// 搜索文章
        /// </summary>
        public async Task<(IEnumerable<Article> Items, int TotalCount)> SearchAsync(string keyword, int pageIndex = 1, int pageSize = 20)
        {
            var query = _context.Articles
                .Include(a => a.Category)
                .Where(a => a.Status == 1 && // 只搜索已发布的文章
                           (a.Title.Contains(keyword) ||
                            (a.Content != null && a.Content.Contains(keyword)) ||
                            (a.Summary != null && a.Summary.Contains(keyword)) ||
                            (a.Tags != null && a.Tags.Contains(keyword))));

            var totalCount = await query.CountAsync();
            var items = await query
                .OrderByDescending(a => a.ViewCount)
                .ThenByDescending(a => a.CreatedAt)
                .Skip((pageIndex - 1) * pageSize)
                .Take(pageSize)
                .ToListAsync();

            return (items, totalCount);
        }

        /// <summary>
        /// 检查Slug是否存在
        /// </summary>
        public async Task<bool> SlugExistsAsync(string slug, long? excludeId = null)
        {
            var query = _context.Articles.Where(a => a.Slug == slug && a.Status != 0);
            
            if (excludeId.HasValue)
            {
                query = query.Where(a => a.Id != excludeId.Value);
            }
            
            return await query.AnyAsync();
        }

        /// <summary>
        /// 添加文章
        /// </summary>
        async Task IArticleRepository.AddAsync(Article entity)
        {
            try
            {
                entity.CreatedAt = DateTime.UtcNow;
                entity.UpdatedAt = DateTime.UtcNow;
                
                await base.AddAsync(entity);
                await SaveChangesAsync();
                
                _logger?.LogInformation("Article added successfully with ID: {ArticleId}", entity.Id);
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "Failed to add article with title: {Title}", entity.Title);
                throw;
            }
        }

        /// <summary>
        /// 获取所有文�?
        /// </summary>
        async Task<IEnumerable<Article>> IArticleRepository.GetAllAsync()
        {
            return await _context.Articles
                .Include(a => a.Category)
                .Where(a => a.Status != 0) // 排除已删�?
                .OrderByDescending(a => a.CreatedAt)
                .ToListAsync();
        }

        /// <summary>
        /// 更新文章
        /// </summary>
        async Task IArticleRepository.UpdateAsync(Article entity)
        {
            try
            {
                entity.UpdatedAt = DateTime.UtcNow;
                _context.Articles.Update(entity);
                await SaveChangesAsync();
                
                _logger?.LogInformation("Article updated successfully with ID: {ArticleId}", entity.Id);
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "Failed to update article with ID: {ArticleId}", entity.Id);
                throw;
            }
        }

        #endregion
    }
}
